<template>
  <q-dialog
    v-model="dialogFlag"
    @show="
      () => {
        if (!image) return;
        cropper = new Cropper(image, {
          preview: '.preview',
          aspectRatio: 1 / 1,
        });
      }
    "
  >
    >
    <input
      v-show="false"
      ref="inputRef"
      type="file"
      name="image"
      accept="image/*"
      @change="
        (e) => {
          setImage(e);
        }
      "
    />
    <q-card style="width: 700px; max-width: 80vw">
      <q-card-section>
        <div class="text-h6">上传头像</div>
      </q-card-section>
      <q-card-section class="row q-pa-none justify-center">
        <div>
          <div style="height: 220px; width: 350px">
            <img
              v-show="imgSrc"
              ref="image"
              style="max-width: 100%"
              :src="imgSrc"
            />
            <div
              v-show="!imgSrc"
              class="bg-grey-7 full-width full-height"
            ></div>
          </div>
        </div>
        <div class="q-pl-xl">
          <p>预览</p>
          <div
            class="preview"
            style="
              overflow: hidden;
              height: 150px;
              width: 150px;
              border-radius: 50%;
            "
          ></div>
        </div>
      </q-card-section>
      <q-card-section>
        <div>
          <q-btn @click="zoom(0.2)"> 放大 </q-btn>
          <q-btn @click="zoom(-0.2)"> 缩小 </q-btn>
          <q-btn @click="move(-10, 0)"> 左移 </q-btn>
          <q-btn @click="move(10, 0)"> 右移 </q-btn>
          <q-btn @click="move(0, -10)">上移</q-btn>
          <q-btn @click="move(0, 10)">下移</q-btn>
          <q-btn @click="rotate(90)"> 旋转+90度 </q-btn>
          <q-btn @click="rotate(-90)"> 旋转-90度 </q-btn>
          <q-btn @click="reset()"> 重置 </q-btn>
        </div>
        <div class="flex justify-between q-pt-sm">
          <q-btn color="positive" @click="showFileChooser()"> 上传图片 </q-btn>
          <q-btn
            :loading="loadBtn"
            color="primary"
            :disable="imgSrc == ''"
            @click="cropImage()"
          >
            上传
          </q-btn>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import {
  globalDelImg,
  settingChangeAvatar,
  globalUploadBase64Img,
} from 'src/service/api';
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';
import { useWebStore } from 'src/stores/webStore';
import { useYuan } from 'src/use';
import { ref } from 'vue';
import { dialogFlag, userInfo } from './shared';
const webStore = useWebStore();
const { Ok, Warn } = useYuan();
/* 上传图片相关 */
const inputRef = ref<HTMLInputElement | null>();
const image = ref<HTMLImageElement>();
const cropper = ref<Cropper>();
const imgSrc = ref('');
const loadBtn = ref(false);
const cropImage = () => {
  if (!cropper.value) return;
  loadBtn.value = true;
  globalUploadBase64Img(cropper.value.getCroppedCanvas().toDataURL()).then(
    ({ data, error }) => {
      if (!error) {
        const updateImg = () => {
          userInfo.value.avatar = data.url;
          settingChangeAvatar({ avatar: userInfo.value.avatar }).then(
            ({ error: err1 }) => {
              if (!err1) {
                webStore.userInfo.avatar = data.url;
                dialogFlag.value = false;
                imgSrc.value = '';
                Ok('用户信息更新成功');
              }
              loadBtn.value = false;
            },
          );
        };
        if (userInfo.value.avatar) {
          globalDelImg({ href: userInfo.value.avatar }).then(
            ({ error: err2 }) => {
              if (!err2) {
                updateImg();
              }
            },
          );
        } else {
          updateImg();
        }
      }
    },
  );
};
const move = (offsetX: number, offsetY: number) => {
  cropper.value?.move(offsetX, offsetY);
};
const reset = () => {
  cropper.value?.reset();
};
const rotate = (deg: number) => {
  cropper.value?.rotate(deg);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const setImage = (e: any) => {
  const file = e.target?.files[0];
  if (file.type.indexOf('image/') === -1) {
    Warn('请选择图片文件！');
    return;
  }
  if (typeof FileReader === 'function') {
    const reader = new FileReader();
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    reader.onload = (event: any) => {
      if (!event.target) return;
      imgSrc.value = event.target.result;
      cropper.value?.replace(event.target.result);
    };
    reader.readAsDataURL(file);
  } else {
    Warn('抱歉, 您的浏览器不支持FileReader API!');
  }
};
const showFileChooser = () => {
  inputRef.value?.click();
};
const zoom = (percent: number) => {
  cropper.value?.zoom(percent);
};
</script>

<style scoped></style>
